<template>
    <div class="forum-detail-container">
      <!-- 话题详情 -->
      <div class="topic-detail glassmorphism" v-if="topic">
        <div class="topic-header">
          <img :src="'http://localhost:8092' + topic.avatar" class="author-avatar" />
          <div class="author-info">
            <span class="nickname">{{ topic.nickname }}</span>
            <span class="post-time">{{ formatDate(topic.createdAt) }}</span>
          </div>
        </div>
        <div class="topic-content">
          <h1 class="topic-title">{{ topic.topic }}</h1>
        </div>
        <div class="interaction-bar">
          <el-button type="info" circle>
            <el-icon><ChatDotRound /></el-icon>
          </el-button>
          <el-button type="danger" circle>
            <el-icon><Star /></el-icon>
          </el-button>
        </div>
      </div>
  
      <!-- 评论输入框 -->
      <div class="comment-form glassmorphism">
        <el-input
          v-model="newComment"
          type="textarea"
          :rows="3"
          placeholder="写下你的评论..."
          maxlength="200"
          show-word-limit
        />
        <div class="submit-btn">
          <el-button 
            type="primary" 
            @click="submitComment"
            :loading="commentLoading"
          >
            发表评论
          </el-button>
        </div>
      </div>
  
      <!-- 评论列表 -->
      <div class="comment-list">
    <div 
      class="comment-item glassmorphism"
      v-for="comment in comments"
      :key="comment.comment_id"
    >
      <div class="comment-header">
        <img :src="'http://localhost:8092' + comment.avatar" class="author-avatar" />
        <div class="comment-author">
          <span class="nickname">{{ comment.nickname }}</span>
          <span class="comment-time">{{ formatDate(comment.createdAt) }}</span>
        </div>
      </div>
      <div class="comment-content">
        {{ comment.comment }}
      </div>
    </div>
  </div>
  
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-box">
        <el-icon class="loading-icon" :size="30"><Loading /></el-icon>
        加载中...
      </div>
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted } from 'vue'
  import { useRoute } from 'vue-router'
  import axios from 'axios'
  import { ElMessage } from 'element-plus'
  import { ChatDotRound, Star, Loading } from '@element-plus/icons-vue'
  
  const route = useRoute()
  const topicId = ref('')
  const topic = ref(null)
  const loading = ref(true)
  const userInfo = ref(null)
  // 评论相关状态
  const newComment = ref('')
  const commentLoading = ref(false)
  const comments = ref([])
  
  // 模拟初始评论数据
  const fetchComments = async () => {
  try {
    const { data } = await axios.get('http://localhost:8092/comment/getCommentByTopicId', {
      params: { topicId: topicId.value }
    })
    
    if (data.code === 200) {
      comments.value = data.data
      console.log('获取到的评论:', comments.value)
    } else if (data.code === 404) {
      comments.value = []
      ElMessage.warning('暂无评论')
    }
  } catch (error) {
    console.error('获取评论失败:', error)
    ElMessage.error('评论加载失败')
  }
}
  
  // 日期格式化
  const formatDate = (date) => {
    return new Date(date).toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    })
  }
  
  // 获取话题详情
  const fetchTopicDetail = async () => {
  try {
    const { data } = await axios.get('http://localhost:8092/topic/getTopicByTopicId', {
      params: { topicId: topicId.value }
    })
    
    if (data.code === 200 && data.data.length > 0) {
      topic.value = data.data[0]
      await fetchComments() // 获取话题成功后获取评论
    } else {
      ElMessage.warning('话题不存在')
    }
  } catch (error) {
    ElMessage.error('加载失败')
    console.error('接口错误:', error)
  } finally {
    loading.value = false
  }
}
  
  // 提交评论
  const submitComment = async () => {
  try {
    // 表单验证
    if (!newComment.value.trim()) {
      ElMessage.warning('请输入评论内容')
      return
    }
    
    // 登录状态检查
    if (!userInfo.value?.userId) {
      ElMessage.warning('请先登录')
      return
    }

    commentLoading.value = true
    
    // 构造请求数据
    const commentData = {
      comment: newComment.value,
      topicId: Number(topicId.value),
      userId: userInfo.value.userId,
      nickname: userInfo.value.nickname,
      avatar: userInfo.value.avatar
    }

    // 调用后端接口
    const { data } = await axios.post(
      'http://localhost:8092/comment/create',
      commentData
    )

    if (data.code === 200) {
      ElMessage.success('评论成功')
      newComment.value = ''
      await fetchComments() // 重新获取最新评论
    } else {
      ElMessage.error(data.msg || '评论失败')
    }
  } catch (error) {
    console.error('评论失败:', error)
    ElMessage.error('评论失败，请稍后重试')
  } finally {
    commentLoading.value = false
  }
}
// 在获取话题详情时获取用户信息
const fetchUserDetail = async (userId) => {
  try {
    const { data } = await axios.get(`http://localhost:8092/user/getUserDetailById`, {
      params: { userId }
    })
    
    if (data?.code === 200) {
      userInfo.value = data.data[0] || null
    }
  } catch (error) {
    console.error("用户信息加载失败", error)
  }
}

  
onMounted(async () => {
  topicId.value = route.query.topicId
  if (topicId.value) {
    const userId = route.query.userId 
    if (userId) {
      await fetchUserDetail(userId)
      await fetchTopicDetail()
    } else {
      ElMessage.error('请先登录')
      loading.value = false
    }
  } else {
    ElMessage.error('缺少话题ID')
    loading.value = false
  }
})
  </script>
  
  <style scoped>
  .forum-detail-container {
    max-width: 800px;
    margin: 0 auto;
    padding: 20px;
    font-family: 'Helvetica Neue', Helvetica, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', Arial, sans-serif;
  }
  
  .glassmorphism {
    background: rgba(255, 255, 255, 0.9);
    backdrop-filter: blur(10px);
    border-radius: 12px;
    padding: 20px;
    margin-bottom: 20px;
    box-shadow: 0 4px 30px rgba(0, 0, 0, 0.1);
    border: 1px solid rgba(255, 255, 255, 0.3);
  }
  
  .topic-header {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
  }
  
  .author-avatar {
    width: 50px;
    height: 50px;
    border-radius: 50%;
    margin-right: 15px;
    object-fit: cover;
  }
  
  .author-info {
    display: flex;
    flex-direction: column;
  }
  
  .nickname {
    font-weight: 600;
    color: #2c3e50;
  }
  
  .post-time {
    color: #7f8c8d;
    font-size: 0.9em;
  }
  
  .topic-content {
    margin-bottom: 20px;
  }
  
  .topic-title {
    font-size: 1.8em;
    color: #34495e;
    line-height: 1.6;
    margin: 0;
  }
  
  .interaction-bar {
    display: flex;
    gap: 15px;
    padding-top: 15px;
    border-top: 1px solid #eee;
  }
  
  .comment-form {
    margin: 30px 0;
  }
  
  .submit-btn {
    margin-top: 15px;
    text-align: right;
  }
  
  .comment-item {
    margin-bottom: 15px;
    transition: all 0.3s ease;
  }
  
  .comment-item:hover {
    transform: translateX(5px);
  }
  
  .comment-header {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
  }
  
  .comment-avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    margin-right: 12px;
  }
  
  .comment-author {
    display: flex;
    flex-direction: column;
  }
  
  .comment-time {
    color: #7f8c8d;
    font-size: 0.85em;
  }
  
  .comment-content {
    color: #34495e;
    line-height: 1.6;
    padding-left: 52px;
  }
  
  .loading-box {
    text-align: center;
    padding: 50px 0;
    color: #7f8c8d;
  }
  
  .loading-icon {
    animation: rotating 2s linear infinite;
    margin-bottom: 10px;
  }
  
  @keyframes rotating {
    from { transform: rotate(0deg); }
    to { transform: rotate(360deg); }
  }
  </style>